;(function ($) {
    var count = 0;
    var subjectData =null;
    var parasMap = [];
    var parentSelectPrefix = "parent-subject-";
    var childSelectPrefix = "child-subject-";
    var confirmBtnPrefix = "confirm-btn-subject-";
    var parentList = new Array();

    /**
     * 获取所有初始选中的专业ID串
     * @param contextId 显示专业内容区域的ID
     */
    $.getAllSubjectIds = function(contextId) {
        var subjectList = $("#"+contextId).find("p[data-subject]");
        var ids = '';
        if(subjectList !=null && subjectList.length > 0){
            $.each(subjectList,function (index,subject) {
                var subject = $(subject).data('subject');
                if(index < subjectList.length  -1){
                    ids += subject +"*";
                }else{
                    ids += subject;
                }
            });
        }
        return ids;
    };

    /**
     * 初始化专业插件
     * @param obj 参数
     {
          element:'elementId',//初始化专业select元素的ID
          context:'contextId',//显示专业/科目名字内容ID
          subjectText:'请选择专业',//父级专业初始显示内容，默认=请选择专业
          childSubjectText:'全部科目',//子级专业初始显示内容，默认=全部科目
          notMultiple:false,//子级科目是否多选，默认否（false）
          confirmBtn:true,//是否显示内容区的删除按钮，默认显示（true）
          initSelect:true,//是否显示初始化的select标签，默认显示（true）
          confirmBtn:true,//是否显示确认按钮，默认显示（true）
          removeBtn:true,//内容区中的删除专业按钮，默认显示
          initData:',2,3,*,4,6,7,*,15,',//初始化显示的专业数据，默认不设置
          style:true,//是否初始化样式,默认是（true）
          width:250,//宽，单位（px）
          selectCallback:function(subjectIds){//选择回调
          },
          removeCallback:function(parentId,subjectIds){//删除回调
          },
          confirmCallback:function(parentId,subjectIds){//点击确认回调
          },
          successCallback:function(){//初始化成功
          }
      }
     */
    $.initSubject = function (obj) {
        try{
            count ++;
            parasMap[count]  = obj;
            if(subjectData ==null){
                subjectData = findLayeredSubjectList();
            }
            if(typeof parasMap[count].initSelect=='undefined' || parasMap[count].initSelect==true){
                var selectEm = document.createElement('select');
                var classText = '';
                if(typeof parasMap[count].classText !='undefined'){
                    classText = parasMap[count].classText;
                }
                selectEm.setAttribute("class",parentSelectPrefix+count +" chosen-select "+classText);
                if(typeof parasMap[count].width !='undefined' && /^[1-9]+[0-9]*$/.test(parasMap[count].width)){
                    selectEm.setAttribute('style','width: '+parasMap[count].width+'px;');
                }else{
                    selectEm.setAttribute('style','width: 200px;');
                }
                var opEm = document.createElement('option');
                opEm.value = 0;
                var subjectText = obj.subjectText;
                if(typeof subjectText =='undefined' || subjectText== null || $.trim(subjectText)==''){
                    subjectText = '请选择专业';
                }
                selectEm.setAttribute('data-placeholder',subjectText);
                opEm.innerHTML = subjectText;
                if(subjectData!=null && subjectData!=undefined && subjectData!=""){
                    selectEm.appendChild(opEm);
                    $.each(subjectData[0],function (index,subject) {
                        opEm = document.createElement('option');
                        opEm.value = subject.id;
                        opEm.innerHTML = subject.subjectName;
                        selectEm.appendChild(opEm);
                    });
                }
                document.getElementById(parasMap[count].element).appendChild(selectEm);
                //初始化子级专业的select
                initChildSubject(0,count);
                parentList.push({index:count,selectEm:selectEm});
                //判断是否需要初始化样式
                if(typeof parasMap[count].style =='undefined' ||parasMap[count].style==true){
                    $(selectEm).trigger("liszt:updated");
                    $(selectEm).chosen();
                }
                //初始化父级专业select
                intiParentSelected();
            }

            if(typeof parasMap[count].initData !='undefined' && $.trim( parasMap[count].initData) !=''){
                initShowText(parasMap[count].initData,count);
            }
            if($.isFunction(parasMap[count].successCallback)){
                parasMap[count].successCallback();
            }
        }catch (e) {
            console.info("--------- init subject error",e);
        }
    }

    /**
     * 初始化子级专业数据
     * @param params 参数
     * @param index 元素下标
     * @param parentId 父专业ID
     */
    function initChildSubject(parentId,index) {
        //获取子级专业的select
        var childSelectEm = getChildSelect(index);
        if(parentId > 0 && $.trim(parentId) !=''){
            var childSubjectList = subjectData[parentId];
            if(childSubjectList!=null && childSubjectList.length > 0){
                $.each(childSubjectList,function (index,childSubject) {
                    var opEm = document.createElement('option');
                    opEm.value = childSubject.id;
                    opEm.innerHTML = childSubject.subjectName;
                    childSelectEm.appendChild(opEm);
                });
            }
        }
        document.getElementById(parasMap[index].element).appendChild(childSelectEm);
        //是否显示确认按钮
        if(typeof parasMap[index].confirmBtn =='undefined' || parasMap[index].confirmBtn==true){
            document.getElementById(parasMap[index].element).appendChild(getConfirmBtn(index));
        }
        childSelectEm.onchange = function () {
            selectCallback(index);
        }
        //判断是否需要初始化样式
        if(typeof parasMap[index].style =='undefined' ||parasMap[index].style==true){
            $(childSelectEm).trigger("liszt:updated");
            $(childSelectEm).chosen();
        }
    }

    /**
     * 获取子级专业的select
     * @param index 元素下标
     * @returns {HTMLSelectElement}
     */
    function getChildSelect(index) {
        var childSelectEm = document.createElement('select');
        var childClassName = childSelectPrefix+index;
        var classText = '';
        if(typeof parasMap[index].classText !='undefined'){
            classText = parasMap[index].classText;
        }
        childSelectEm.setAttribute("class",childClassName+" chosen-select "+classText);

        //添加子级第一个元素
        var opEm = document.createElement('option');
        opEm.value = 0;
        var childSubjectText = parasMap[index].childSubjectText;
        if(typeof childSubjectText =='undefined' || childSubjectText== null || $.trim(childSubjectText)==''){
            childSubjectText = '请选择科目';
        }
        var notMultiple = parasMap[index].notMultiple;
        if(typeof  notMultiple =='undefined'|| notMultiple == false){
            opEm.setAttribute("disabled","disabled");
            childSelectEm.setAttribute("multiple","multiple");
        }
        opEm.innerHTML = childSubjectText;
        if(typeof parasMap[index].width !='undefined' && /^[1-9]+[0-9]*$/.test(parasMap[index].width)){
            childSelectEm.setAttribute('style','margin-left: 10px;width: '+parasMap[index].width+'px;');
        }else{
            childSelectEm.setAttribute('style','margin-left: 10px;max-width: 310px;min-width: 260px;');
        }
        childSelectEm.setAttribute('data-placeholder',childSubjectText);
        childSelectEm.appendChild(opEm);
        //删除原有的子select元素
        $("."+childClassName).remove();
        var list = $($("."+parentSelectPrefix+index).parent()).find("div.chosen-container");
        if(list.length > 1){
            $(list[1]).remove();
        }
        return childSelectEm;
    }

    /**
     * 获取确认按钮
     * @param index 元素下标
     * @returns {HTMLButtonElement}
     */
    function getConfirmBtn(index) {
        var btnClassName = confirmBtnPrefix+index;
        $("."+btnClassName).remove();
        var buttonBtn = document.createElement('button');
        buttonBtn.type = 'button';
        buttonBtn.innerHTML = '确认';
        buttonBtn.setAttribute("class",btnClassName+" btn btn-outline btn-primary ml10");
        buttonBtn.setAttribute("style","margin-bottom:0px;");
        buttonBtn.onclick = function (){
            var parentId = $("."+parentSelectPrefix+index).val();
            var childIds = $("."+childSelectPrefix+index).val();
            var subjectIds ='';

            if(parentId > 0){
                subjectIds =',' + parentId;
                //多选
                if(typeof  parasMap[index].notMultiple =='undefined'|| parasMap[index].notMultiple == false){
                    if(childIds !=null){
                        subjectIds += ","+childIds;
                    }
                }else{//非多选
                    if(childIds > 0){
                        subjectIds += ","+childIds;
                    }
                }
                subjectIds +=',';
            }
            //初始化显示专业内容
            initShowText(subjectIds,index);
            //确认回调
            if($.isFunction(parasMap[index].confirmCallback)){
                parasMap[index].confirmCallback(parentId,subjectIds);
            }
        }
        return buttonBtn;
    }

    /**
     * 初始化父级元素的选择
     */
    function intiParentSelected() {
        $.each(parentList,function (index,em) {
            em.selectEm.onchange = function () {
                initChildSubject(this.value,em.index);
                selectCallback(em.index);
            }
        });
    }

    /**
     * 选择回调
     * @param index
     */
    function selectCallback(index) {
        var selectList = $("#"+parasMap[index].element).find("select");
        var subjectIds = '';
        $.each(selectList,function (index,em) {
            if(index==0){
                var parentId = $(em).val();
                if(parentId > 0){
                    subjectIds += parentId +',';
                }
            }else{
                var notMultiple = parasMap[index].notMultiple;
                if(typeof  notMultiple =='undefined'|| notMultiple == false){
                    var childIds = $(em).val();
                    if(childIds !=null){
                        $.each(childIds,function (i,id) {
                            subjectIds += id+',';
                        });
                    }
                }else{
                    var childId = em.value;
                    if(childId > 0){
                        subjectIds += childId+',';
                    }
                }
            }
        });
        if(subjectIds !=''){
            subjectIds = ',' + subjectIds;
        }
        if($.isFunction(parasMap[index].selectCallback)){
            parasMap[index].selectCallback(subjectIds);
        }
    }

    /**
     * 初始化显示内容
     */
    function initShowText(subjectIds,index) {
        if(subjectIds !=''){
            var arr = subjectIds.split("*");
            $.each(arr,function (i,_subjectIds) {
                initText(_subjectIds,index);
            });
        }
    }

    /**
     * 初始化显示内容
     * @param subjectIds
     * @param index
     */
    function initText(subjectIds,index) {
        if(subjectIds !=''){
            var arr = subjectIds.substring(1,subjectIds.length-1).split(",");
            var parentId = arr[0];
            var parentName = '';
            var childNames = '';
            var childIds= new Array();
            if(parentId > 0){
                var parentList = subjectData[0];
                for (var i = 0; i < parentList.length; i++) {
                    if(parentList[i].id == parentId){
                        parentName = parentList[i].subjectName;
                        break;
                    }
                }
                if(arr.length > 1){
                    var childList = subjectData[parentId];
                    var childObj = {};
                    $.each(arr,function (index,id) {
                        if(index > 0){
                            childIds.push(id);
                            childObj[id] = true;
                        }
                    });
                    for (var i = 0; i < childList.length; i++) {
                        var child = childList[i];
                        if(childObj[child.id]==true){
                            childNames += child.subjectName +' / ';
                        }
                    }
                }
            }
            var showText = '';
            if(parentName !=''){
                showText += parentName +' // ';
            }
            if(childNames !=''){
                showText += childNames;
            }else{
                if(parentName !=''){
                    showText ="";
                }
            }
            if(showText !=''){
                showText = showText.substring(0,showText.length -1);
                var pEm = document.createElement('p');
                pEm.setAttribute('data-subject',subjectIds);
                pEm.setAttribute("data-id",parentId);
                pEm.setAttribute("class",'dataSelectSubjects__wrap');
                var aEm = null;
                if(typeof parasMap[index].removeBtn =='undefined' || parasMap[index].removeBtn==true){
                    aEm = document.createElement('a');
                    aEm.setAttribute('data-parent',parentId);
                    aEm.setAttribute('data-child',childIds.length > 0 ?'':childIds);
                    aEm.setAttribute("title",'删除');
                    aEm.setAttribute("class",'fa-close-wrap c-999');
                    aEm.innerHTML = '&nbsp;&nbsp;';
                    var iEm = document.createElement('i');
                    iEm.setAttribute("class",'fa fa-close');
                    aEm.appendChild(iEm);
                }
                pEm.innerHTML = showText;
                if(aEm !=null){
                    pEm.appendChild(aEm);
                    aEm.onclick = function () {//删除
                        var _this = $(this);
                        var _parentId = _this.data('parent');
                        var subjectIds = _this.parent().data('subject');
                        _this.parent().remove();
                        if($.isFunction(parasMap[index].removeCallback)){
                            parasMap[index].removeCallback(_parentId,subjectIds);
                        }
                    }
                }
                var oldList = $("#"+parasMap[index].context).find("[data-id='"+parentId+"']");
                if(oldList.length > 0){
                    oldList.remove();
                }
                document.getElementById(parasMap[index].context).appendChild(pEm);
            }
        }
    }

}(jQuery));